import yaml
import json
import warnings
from app.pdf_extract_kit.registry.registry import TASK_REGISTRY, MODEL_REGISTRY
from app.project.doc_to_recommendation.utils.paths import DEFAULT_PATH, solve_path
from app.project.doc_to_recommendation.utils.log_utils import get_logger

logger = get_logger(__name__)

def load_config(config_path, mode = "yaml"):
    if config_path is None:
        warnings.warn(
            "Configuration path is None. Please provide a valid configuration file path. "
        )
        logger.warning("Configuration path is None. Please provide a valid configuration file path.")
        return None

    config_path = solve_path(config_path)
    with open(config_path, 'r', encoding='utf-8') as file:
        if mode == "yaml":
            config = yaml.safe_load(file)
            config_sub_path_solve(config)
        elif mode == "json":
            config = json.load(file)
    return config

def config_sub_path_solve(config: dict):
    for key, value in config.items():
        if any(pattern in key for pattern in ['dir', 'path', 'outputs', 'inputs']):
            logger.debug(f"Before solve_path Config name: {key}, Config value: {value}")
            config[key] = solve_path(value)
            logger.debug(f"After solve_path Config name: {key}, Config value: {value}")
        elif isinstance(value, dict):
            config_sub_path_solve(value)

def get_config_path(config_name):
    return DEFAULT_PATH["_CONFIG_PATH/"] / config_name


def initialize_tasks_and_models(config):

    task_instances = {}
    for task_name in config['tasks']:

        model_name = config['tasks'][task_name]['model']
        model_config = config['tasks'][task_name]['model_config']
        TaskClass = TASK_REGISTRY.get(task_name)
        ModelClass = MODEL_REGISTRY.get(model_name)

        model_instance = ModelClass(model_config)
        task_instance = TaskClass(model_instance)

        task_instances[task_name] = task_instance

    return task_instances